package com.tsinghuabigdata.edu.ddmath.view;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.tsinghuabigdata.edu.ddmath.R;

public class GenderSelectorView extends LinearLayout implements View.OnClickListener {

    //
    private LinearLayout llGirl;
    private LinearLayout llBoy;
    private ImageView rbBoy;
    private ImageView rbGirl;

    /**
     * 选中状态
     * 男 10    二进制表示
     * 女 01
     */
    private int selGender = BOY;
    private int checkedGender = BOY;
    private int currentChecked = BOY;
    public static final int BOY = 2;
    public static final int GIRL = 1;

    private View root;

    public GenderSelectorView(Context context) {
        super(context);
        initialize();
    }

    public GenderSelectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public GenderSelectorView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initialize();
    }

    /**
     * 初始化界面元素
     */
    private void initialize() {
        root = inflate(getContext(), R.layout.layout_gender, this);

        llBoy = (LinearLayout) findViewById(R.id.ll_boy);
        llGirl = (LinearLayout) findViewById(R.id.ll_girl);
        rbBoy = (ImageView) findViewById(R.id.rb_boy);
        rbGirl = (ImageView) findViewById(R.id.rb_girl);


        rbBoy.setSelected(true);
        rbBoy.setOnClickListener(this);
        rbGirl.setOnClickListener(this);
        llBoy.setOnClickListener(this);
        llGirl.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_boy:
            case R.id.rb_boy:
                currentChecked = BOY;
                toggleGender();
                break;
            case R.id.ll_girl:
            case R.id.rb_girl:
                currentChecked = GIRL;
                toggleGender();
                break;
        }
    }

    private void toggleGender() {
        if (selGender == currentChecked){
            return;
        }
        if (selGender == GIRL) {
            selGender = BOY;
            rbBoy.setSelected(true);
            rbGirl.setSelected(false);
        } else {
            selGender = GIRL;
            rbBoy.setSelected(false);
            rbGirl.setSelected(true);
        }
    }

    public int getSelGender() {
        return selGender;
    }

    public void setSelGender(int selGender) {
        if ( this.selGender != selGender){
            currentChecked = selGender;
            toggleGender();
        }
    }
}
